package top.linyuxb.lycloud.admin.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.linyuxb.lycloud.admin.constant.StatusEnum;
import top.linyuxb.lycloud.admin.entity.LyCloudUserEntity;
import top.linyuxb.lycloud.admin.entity.LyConfNodeEntity;
import top.linyuxb.lycloud.admin.entity.LyConfProjectEntity;
import top.linyuxb.lycloud.admin.repository.LyConfNodeRepository;
import top.linyuxb.lycloud.admin.repository.LyConfProjectRepository;
import top.linyuxb.lycloud.admin.service.ILyConfPermissionService;
import top.linyuxb.lycloud.admin.service.impl.LoginService;
import top.linyuxb.lycloud.admin.service.impl.LyConfNodeServiceImpl;
import top.linyuxb.lycloud.admin.utils.ReturnT;

import java.util.*;

import static top.linyuxb.lycloud.admin.web.interceptor.EnvInterceptor.CURRENT_ENV;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/29 14:43
 * @Desc: 配置管理
 */
@Controller
@RequestMapping("/conf")
public class ConfController {
    @Resource
    private LyConfNodeRepository lyConfNodeRepository;
    @Resource
    private LyConfProjectRepository lyConfProjectRepository;
    @Resource
    private LyConfNodeServiceImpl lyConfNodeService;
    @Resource
    private ILyConfPermissionService lyConfPermissionService;

    @RequestMapping("")
    public String index(HttpServletRequest request, Model model, String app) {
        List<LyConfProjectEntity> list = lyConfProjectRepository.findAll();
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("系统异常，无可用项目");
        }
        LyCloudUserEntity loginUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        Set<String> thisApps = new HashSet<>();
        Boolean permissionApps = lyConfPermissionService.getPermissionApps(loginUser, thisApps);
        list.removeIf(project -> !permissionApps && !thisApps.contains(project.getApp()));
        LyConfProjectEntity project = null;
        if (CollectionUtils.isNotEmpty(list)) {
            project = list.get(0);
            for (LyConfProjectEntity item : list) {
                if (item.getApp().equals(app)) {
                    project = item;
                }
            }
        }
        boolean ifHasProjectPermission = false;
        if (Objects.nonNull(project)) {
            ifHasProjectPermission = lyConfPermissionService.ifHasProjectPermission(
                    loginUser, (String) request.getAttribute(CURRENT_ENV), project.getApp()
            );
        }
        model.addAttribute("projectList", list);
        model.addAttribute("project", project);
        model.addAttribute("ifHasProjectPermission", ifHasProjectPermission);

        return "conf/conf.index";
    }

    @ResponseBody
    @RequestMapping("/pageList")
    public Map<String, Object> pageList(HttpServletRequest request,
                                        @RequestParam(required = false, defaultValue = "0") int start,
                                        @RequestParam(required = false, defaultValue = "10") int length,
                                        String app,
                                        String key) {
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        String loginEnv = (String) request.getAttribute(CURRENT_ENV);
        return lyConfNodeService.pageList(start, length, app, key, lyCloudUser, loginEnv);
    }

    /**
     * get
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete")
    public ReturnT<String> delete(HttpServletRequest request,
                                  @RequestParam(value = "id") Long id) {
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        String loginEnv = (String) request.getAttribute(CURRENT_ENV);
        ReturnT<String> delete = lyConfNodeService.delete(id, lyCloudUser, loginEnv);
        lyConfNodeRepository.findById(id).ifPresent(
                lyConfNode -> lyConfNodeService.refreshConf(loginEnv, lyConfNode.getApp())
        );
        return delete;
    }

    /**
     * create/update
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/add")
    public ReturnT<String> add(HttpServletRequest request, LyConfNodeEntity lyConfNode) {
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        String loginEnv = (String) request.getAttribute(CURRENT_ENV);
        lyConfNode.setEnv(loginEnv);

        ReturnT<String> add = lyConfNodeService.add(lyConfNode, lyCloudUser, loginEnv);
        lyConfNodeService.refreshConf(loginEnv, lyConfNode.getApp());
        return add;
    }

    /**
     * create/update
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/update")
    public ReturnT<String> update(HttpServletRequest request, LyConfNodeEntity lyConfNode) {
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        String loginEnv = (String) request.getAttribute(CURRENT_ENV);
        lyConfNode.setEnv(loginEnv);

        ReturnT<String> update = lyConfNodeService.update(lyConfNode, lyCloudUser, loginEnv);
        lyConfNodeRepository.findById(lyConfNode.getId())
                .ifPresent(lyConfNode1 ->  lyConfNodeService.refreshConf(lyConfNode1.getEnv(), lyConfNode1.getApp()));
        return update;
    }

}
